package com.demo2.todo.utils;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import com.demo2.todo.model.entity.User;
import com.demo2.todo.exception.UnauthorizedException;

import java.util.Objects;

/**
 * @author evi
 */
public class SecurityUtils {

    /**
     * 获取当前登录用户
     */
    public static User getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            throw new UnauthorizedException("未登录");
        }

        Object principal = authentication.getPrincipal();
        if (principal instanceof User) {
            return (User) principal;
        }

        throw new UnauthorizedException("无法获取用户信息");
    }

    /**
     * 检查当前用户是否有权限操作指定资源
     */
    public static void checkPermission(Long resourceUserId) {
        User currentUser = getCurrentUser();
        // 管理员或资源所有者有权限
        if (!Objects.equals(currentUser.getRole(), "ADMIN") &&
                !currentUser.getId().equals(resourceUserId)) {
            throw new UnauthorizedException("没有操作权限");
        }
    }
}
